package top.jianx.music.provider.netease.request;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
//import okhttp3.FormBody;
//import okhttp3.HttpUrl;
//import okhttp3.Request;
//import okhttp3.Response;
import top.jianx.music.base.BaseRequest;
import top.jianx.music.config.Constants;
import top.jianx.music.model.Song;
import top.jianx.music.provider.netease.NeteaseMusicApi;
import top.jianx.music.provider.netease.NeteaseSong;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@AllArgsConstructor
@NoArgsConstructor
@SuppressWarnings("SpellCheckingInspection")
public class NeteaseSearchMusicRequest extends BaseRequest<List<? extends Song>> {
    private String mKeyword;
    private int mPage;

    @Override
    protected HttpRequest buildRequest() {
        HttpRequest requestBuilder = HttpUtil.createRequest(Method.POST, "http://music.163.com/api/linux/forward");
        requestBuilder.header(Constants.REFERER, "http://music.163.com/");


        JSONObject json = new JSONObject();
        json.put("method", "POST");
        json.put("url", "http://music.163.com/api/cloudsearch/pc");
        JSONObject params = new JSONObject();
        params.put("s", mKeyword);
        params.put("type", 1);
        params.put("offset", mPage * Constants.PAGE_SIZE);
        params.put("limit", mPage);
        json.put("params", params);
        String encrypted = NeteaseMusicApi.encrypt(json);
        requestBuilder.form("eparams", encrypted);
        return requestBuilder;
    }

    @Override
    protected List<NeteaseSong> parseResult(HttpResponse response) throws IOException {
        String body = responseBodyToString(response);
        JSONObject responseJson = JSONObject.parseObject(body);
        JSONObject result = responseJson.getJSONObject("result");
        List<NeteaseSong> songs = new ArrayList<>();
        if (result != null) {
            long songCount = result.getLongValue("songCount");
            JSONArray songArray = result.getJSONArray("songs");
            if (songCount != 0 && songArray != null) {
                songs = songArray.toJavaList(NeteaseSong.class);
            }
        }
        return songs;
    }
}
